# coding: utf8

import consul

from config import config
from utils import logger_util


class ConsulUtil:
    def __init__(self, host, port):
        self.logger = logger_util.get_logger("ConsulUtil")
        self._c = consul.Consul(host=host, port=port)

    def register(self, server_name, ip, port):
        self.logger.info(f"开始注册服务{server_name}")
        check = consul.Check.tcp(ip, port, "10s")  # 健康检查的ip，端口，检查时间
        self._c.agent.service.register(server_name, f"{ip}-{port}",
                                       address=ip, port=port, check=check)  # 注册服务部分
        self.logger.info(f"注册服务{server_name}成功")

    def unregister(self, server_name, ip, port):
        self.logger.info(f"开始退出服务{server_name}")
        self._c.agent.service.deregister(f'{ip}-{port}')

    def get_healthy_service_node(self, service: str):
        res = self._c.health.service(service, passing=True)
        if len(res[1]):
            return res[1]
        return []

    def get_dead_service_node(self, service: str):
        res = self._c.health.state('critical')
        if len(res[1]):
            return res[1]
        return []


CONSUL_CONF = config.get_local_config()['Consul']
consul_util = ConsulUtil(CONSUL_CONF['host'], CONSUL_CONF['port'])
